import levin.levinCommon as levinCommon
from worldArea import WorldArea
import os.path

def loadAll(userc='', worldc=None):
    if worldc is None: worldc= levinCommon.LEVIN_WORLD
    
    print "Loading data", levinCommon.wineWorld, " world from ", worldc
    wineWorld = WorldArea("World")
    levinCommon.wineWorld = wineWorld
    #WorldArea.defaultWorld = levinCommon.wineWorld
    globals()['wineWorld'] = wineWorld
    print wineWorld
    levinCommon.init()
    wineWorld.loadContent(worldc, user=False)
    #wineWorld.loadContent('world3.pk', user=False)
    if not userc : userc = levinCommon.USER_SAVE
    if os.path.exists(userc):
        wineWorld.loadContent(userc,user=True)
    print wineWorld



def addBottle(country, region=None, groupAppellation=None, appellation=None,**args):
    country = wineWorld[country]
    region  = country[region] if region else country
    groupAppellation  = region[groupAppellation] if groupAppellation else region
    appellation  = groupAppellation[appellation] if appellation else groupAppellation

    b = Bottle(country = country , region=region, groupAppellation=groupAppellation, appellation=appellation, parentArea=appellation, **args)

    appellation.addWine( b )


def fillNew(l, fuzzy=True):
    wineWorld = levinCommon.wineWorld
    from wineBase import BottleSet
    atts = ["cru_name",    "millesime",   "volume",     "meanrate" ,     "alcohol",     "productor",     "numInStock",     "pricePerBottle",     "acquireDate",     "acquireComment",     "cepage",     "geolocalisation",     "otherInfo",    "suggestedFrom ",     "suggestedTo",     "optimalMax",     "optimalMin" , "color"]


    countryTR =dict( (v,u)  for u,v in zip( [u'France', u'Italy', u'Spain', u'Portugal', u'Germany', u'Greece', u'USA', u'SouthAfrica', u'Australia', u'Chile', u'Argentina', u'NewZealand', u'TRTR', 'Italy'],
                                         [u'France', u'Italie', u'Espagne', u'Portugal', u'Allemagne', u'Gr\xe8ce', u'\xc9tats-Unis', u'Afrique du Sud', u'Australie', u'Chili', u'Argentine', u'Nouvelle-Z\xe9lande', u'TRTR', 'Italy']) )
    
    regionTR= dict( (v,u) for u,v in zip([u'Burgundy', u'Bordeaux', u'Alsace', u'Rhone Valley', u'Beaujolais', u'South West', u'Champagne', u'Jura', u'Savoy', u'Provence', u'Languedoc-Roussillon', u'Corsica', u'Piemont', u'Tuscany'],
                                         [u'Bourgogne', u'Bordeaux', u'Alsace', u'Vall\xe9e du Rh\xf4ne', u'Beaujolais', u'Sud-Ouest', u'Champagne', u'Jura', u'Savoie', u'Provence', u'Languedoc-Roussillon', u'Corse', u'Pi\xe9mont', u'Toscane']) )


    print l
    rejected = []
    for b in l:
        print b
        print 'adding ' , b.cru_name, b.appellation, b.region
        d ={}
        for a in atts:
            try:
                d[a] = getattr(b,a)
            except:
                pass
        country = countryTR[b.country]
        region = regionTR[b.region]
        countryA = wineWorld[country]
        regionA = wineWorld[country][region]
        #print ' searching for ',b.appellation, '  in ', region
        appellationA = regionA.getSubArea(b.appellation, fuzzy=True)

        if appellationA is None:
            appellationA = regionA[b.appellation]
            print 'YYYY ',appellationA.parentArea
            appellationA.addWine( Bottle(country=country, region=region, appellation= appellationA.name,  **d ) )
            #rejected.append( b )
        else:
            appellationA.addWine( Bottle(country=country, region=region, appellation= appellationA.name,  **d ) )
        #addBottle( , , b.appellation, **d)
    return rejected
                  

import random
def generateRand():
    wineWorld = WorldArea("World")
    levinCommon.wineWorld = wineWorld
    globals()['wineWorld'] = wineWorld
    #print wineWorld
    wineWorld.loadContent('world.pk', user=False)

    for c in ['France', 'Italy']:
        countryA = wineWorld[c] 
        for r in random.sample(countryA.subAreasKeys(), 3):
            regionA = countryA[r]
            #for a in


def loadFromDir(dirname):
    w = WorldArea("World",
                  systemFile = levinCommon.join( dirname, 'world.pk'),
                  userFile   = levinCommon.join( dirname, 'user.pk' ), 
                  )
    #w.loadContent(levinCommon.join( dirname, 'world.pk')w, user=False)
    #w.loadContent(levinCommon.join( dirname, 'user.pk' ),user=True)
    return w

            
def test0():
    import wineAreas, wineBase
    levinCommon.wineWorld = WorldArea("World")
    wineWorld = levinCommon.wineWorld
    wineAreas.translateToNew(wineAreas.wineWorld, wineWorld )
    #return
    rej=fillNew(list(wineBase.BottleSet))
    return rej

def save_wineWorld(fname):
    #import pickle as pk
    #wineWorld.makeWritable()
    pk.dump( levinCommon.wineWorld.toDict(user=False) , open(fname, 'w'), 0 )


def testComp():
    import collections
    bw = WorldArea('fromBase', systemFile='world_fromBase.pk')
    dw = WorldArea('fromData', systemFile='world_fromData.pk')
    di = collections.defaultdict(list)

    bw.compare(dw,di)

    return di

    
def fixwines():
    for b in wineWorld.getWines():
        if b.numInStock is None : b.numInStock = 0
